const Bezier = require('../util/bezier');
const defaultBezier = new Bezier(0.0, 0.0, 0.25, 0.1, 0.25, 1.0, 1.0, 1.0);

module.exports = {
    fly: fly
};

function fly(self, from, to, time, moveType, callback) {
    const lng1 = from.lng;
    const lat1 = from.lat;
    const zoom1 = from.zoom;
    const lng2 = to.lng;
    const lat2 = to.lat;
    const zoom2 = to.zoom;
    const num = Math.ceil(time / 60);

    const startDate = Date.now();
    const detaLng = lng2 - lng1;
    const detaLat = lat2 - lat1;
    const detaZoom = zoom2 - zoom1;
    flyTo.call(self, startDate, time, lng1, lat1, zoom1, detaLng, detaLat, detaZoom, moveType, callback);
}

function flyTo(startDate, totalTime, lng1, lat1, zoom1, detaLng, detaLat, detaZoom, moveType, callback) {
    const time = Date.now() - startDate;
    if (time >= totalTime) {
        this.setLngLat([lng1 + detaLng, lat1 + detaLat]);
        this.setZoom(zoom1 + detaZoom);
        if (callback) callback();
    }
    else {
        let factor = 0;
        if (!moveType || moveType === 'bezier') {
            factor = defaultBezier.get(time / totalTime).y;
        }
        else if (moveType === 'liner') {
            factor = time / totalTime;
        }
        this.setLngLat([lng1 + detaLng * factor, lat1 + detaLat * factor]);
        this.setZoom(zoom1 + detaZoom * factor);
        requestAnimationFrame(flyTo.bind(this, startDate, totalTime, lng1, lat1, zoom1, detaLng, detaLat, detaZoom, moveType, callback));
    }
}